package com.byzk.p2p.admin.money.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.byzk.p2p.admin.admin.vo.AdminUserVo;
import com.byzk.p2p.admin.bank.dto.BankCard;
import com.byzk.p2p.admin.bank.service.BankCardService;
import com.byzk.p2p.admin.base.controller.AdminBaseController;
import com.byzk.p2p.admin.base.util.DateUtils;
import com.byzk.p2p.admin.base.util.JsonMsg;
import com.byzk.p2p.admin.base.util.PageInfo;
import com.byzk.p2p.admin.borrow.service.TenderService;
import com.byzk.p2p.admin.money.dto.WithdrawRecord;
import com.byzk.p2p.admin.money.service.RechargeService;
import com.byzk.p2p.admin.money.service.WithdrawService;
import com.byzk.p2p.admin.money.util.FundRecordType;
import com.byzk.p2p.admin.money.util.WithdrawStatus;
import com.byzk.p2p.admin.money.vo.FundDetailVo;
import com.byzk.p2p.admin.money.vo.WithdrawRecordVo;
import com.byzk.p2p.admin.money.vo.WithdrawUserVo;
import com.byzk.p2p.admin.system.dto.MemberLevel;
import com.byzk.p2p.admin.user.dto.User;
import com.byzk.p2p.admin.user.dto.UserAccount;
import com.byzk.p2p.admin.user.service.UserAccountService;
import com.byzk.p2p.admin.user.service.UserService;
import com.byzk.p2p.admin.user.vo.UserAccountVo;

@Controller
@RequestMapping("/admin/withdraw")
public class WithdrawController extends AdminBaseController {

	@Autowired
	private WithdrawService withdrawService;
	@Autowired
	private UserAccountService userAccountService;
	@Autowired
	private UserService userService;
	@Autowired
	private BankCardService bankCardService;
	@Autowired
	private RechargeService rechargeService;
	
	@Autowired
	private TenderService tenderService;
	/**
	 * 提现列表
	 * @param model 视图对象
	 * @param index 当前页
	 * @param limit 每页条数
	 * @param status 提现状态
	 * @param username 用户名
	 * @param match 匹配符号 EQ("="), GT(">"), LT("<"), GE(">="), LE("<="), NE("<>")
	 * @param money 提现金额
	 * @param createTimeBegin 提现申请时间，开始
	 * @param createTimeEnd 提现申请时间，结束
	 * @param verifyTimeBegin 提现时间，开始
	 * @param verifyTimeEnd 提现时间，结束
	 * @return
	 */
	@RequestMapping(value = "/list")
	public String listWithdraw(Model model,
							@RequestParam(value="index",required=false,defaultValue="1") int index,
							@RequestParam(value="limit",required=false,defaultValue="10") int limit,
							@RequestParam(value="username",required=false) String username,
							@RequestParam(value="match",required=false) String match,
							@RequestParam(value="status",required=false) String status,
							@RequestParam(value="money",required=false) Double money,
						    @RequestParam(value="createTimeBegin",required=false)String createTimeBegin,
						    @RequestParam(value="createTimeEnd",required=false)String createTimeEnd,
						    @RequestParam(value="verifyTimeBegin",required=false)String verifyTimeBegin,
						    @RequestParam(value="verifyTimeEnd",required=false)String verifyTimeEnd,
						    @RequestParam(value="isOffLine",required=false)String isOffLine)throws Exception {
		WithdrawRecordVo withdrawRecordVo = new WithdrawRecordVo();
		withdrawRecordVo.setIndex(index);
		withdrawRecordVo.setLimit(limit);
		if (StringUtils.isNotBlank(username)) {
			withdrawRecordVo.setMatchUser(username);
			model.addAttribute("username", username);
		}
		if (StringUtils.isNotBlank(match)) {
			if (match.equals("EQ")) {
				withdrawRecordVo.setMatchEQ(match);
			}else if (match.equals("GT")) {
				withdrawRecordVo.setMatchGT(match);
			}else if (match.equals("LT")) {
				withdrawRecordVo.setMatchLT(match);
			}else if (match.equals("GE")) {
				withdrawRecordVo.setMatchGE(match);
			}else if (match.equals("LE")) {
				withdrawRecordVo.setMatchLE(match);
			}else if (match.equals("NE")) {
				withdrawRecordVo.setMatchNE(match);
			}
			model.addAttribute("match", match);
		}
		if (StringUtils.isNotBlank(status)) {
			withdrawRecordVo.setStatus(status);
			model.addAttribute("status", status);
		}
		if (money != null) {
			withdrawRecordVo.setMoney(money);
			model.addAttribute("money", money);
		}
		if (StringUtils.isNotBlank(isOffLine)&&"1".equals(isOffLine)) {
			withdrawRecordVo.setIsOffLine("1");
			model.addAttribute("isOffLine", isOffLine);
		}
		if (StringUtils.isNotBlank(createTimeBegin)) {
			withdrawRecordVo.setPublishTimeStart(DateUtils.getRealDate(DateUtils.convert(createTimeBegin, DateUtils.YEAR_MOUTH_DAY_FORMAT)));
			model.addAttribute("createTimeBegin", createTimeBegin);
		}
		if (StringUtils.isNotBlank(createTimeEnd)) {
			withdrawRecordVo.setPublishTimeEnd(DateUtils.getFullDate(DateUtils.convert(createTimeEnd, DateUtils.YEAR_MOUTH_DAY_FORMAT)));
			model.addAttribute("createTimeEnd", createTimeEnd);
		}
		if (StringUtils.isNotBlank(verifyTimeBegin)) {
			withdrawRecordVo.setVerifyTimeBegin(DateUtils.getRealDate(DateUtils.convert(verifyTimeBegin, DateUtils.YEAR_MOUTH_DAY_FORMAT)));
			model.addAttribute("verifyTimeBegin", verifyTimeBegin);
		}
		if (StringUtils.isNotBlank(verifyTimeEnd)) {
			withdrawRecordVo.setVerifyTimeEnd(DateUtils.getFullDate(DateUtils.convert(verifyTimeEnd, DateUtils.YEAR_MOUTH_DAY_FORMAT)));
			model.addAttribute("verifyTimeEnd", verifyTimeEnd);
		}
		PageInfo<WithdrawRecordVo> pageInfo = withdrawService.listWithdrawByStatus(withdrawRecordVo);
		model.addAttribute("pageInfo", pageInfo);
		return ftl(Thread.currentThread().getStackTrace());
	}

	/**
	 * 获取提现用户详细信息
	 * 
	 * @param uid
	 * @return
	 */
	@RequestMapping(value = "/user/detail")
	public String withdrawUserDetail(@RequestParam("uid") Integer uid) {
		try {
			WithdrawUserVo vo = withdrawService.getWithdrawUserDetail(uid);
			super.printJSON(new JsonMsg(-1, "操作成功", vo));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	@RequestMapping(value = "/detail")
	public String withdrawDetail(@RequestParam("id") Integer id) {
		try {
			WithdrawRecord detail = withdrawService.getWithdrawDetail(id);
			super.printJSON(new JsonMsg(-1, "操作成功", detail));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	@RequestMapping(value = "/status/change")
	public void changeStatus(@RequestParam("status") String status, @RequestParam("remark") String remark,
			@RequestParam("id") Integer id) {
		try {
			AdminUserVo adminvo=(AdminUserVo) session.getAttribute("sysUser");
			if (adminvo == null) {
				super.printJSON(new JsonMsg(0, "请先登录"));
				return;
			}
			WithdrawRecord detail = withdrawService.getWithdrawDetail(id);
			if("apply_failure".equals(detail.getStatus()) || "success".equals(detail.getStatus()) || "failure".equals(detail.getStatus())){
				super.printJSON(new JsonMsg(2, "不能重复提现"));
				return;
			}
			if ("transfer".equals(status)) {
				detail.setStatus(WithdrawStatus.TRANSFER);
			} else if ("apply_failure".equals(status)) {
				detail.setStatus(WithdrawStatus.APPLY_FAILURE);
			} else if ("success".equals(status)) {
				detail.setStatus(WithdrawStatus.SUCCESS);
			} else if ("failure".equals(status)) {
				detail.setStatus(WithdrawStatus.FAILURE);
			}
			detail.setTerminal("PC");
			if (withdrawService.transfer(detail)) {
				super.printJSON(new JsonMsg(-1, "操作成功"));
				return;
			}else{
				super.printJSON(new JsonMsg(1, "操作失败"));
				return;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 批量转账
	 * @param ids 提现记录id
	 * @param status 状态
	 * @param remark 备注
	 */
	@RequestMapping(value = "batch/transfer",method=RequestMethod.POST)
	public void batchTransfer(@RequestParam String ids,
								@RequestParam("status") String status,
								@RequestParam("remark") String remark) {
		try {
			AdminUserVo adminvo = (AdminUserVo) session.getAttribute("sysUser");
			if (adminvo == null) {
				super.printJSON(new JsonMsg(0, "请先登录"));
				return;
			}
			if (StringUtils.isBlank(ids)) {
				super.printJSON(new JsonMsg(1, "请勾选状态为转账中的提现"));
				return;
			}
			List<Integer> recordIds = splitID(ids);
			JsonMsg jsonMsg = new JsonMsg(-1, "操作成功");
			if (CollectionUtils.isNotEmpty(recordIds)) {
				for (Integer id : recordIds) {
					WithdrawRecord detail = withdrawService.getWithdrawDetail(id);
					if("apply_failure".equals(detail.getStatus()) || "success".equals(detail.getStatus()) || "failure".equals(detail.getStatus())){
						jsonMsg = new JsonMsg(2, "不能重复提现");
						break;
					}
					if ("transfer".equals(status)) {
						detail.setStatus(WithdrawStatus.TRANSFER);
					} else if ("apply_failure".equals(status)) {
						detail.setStatus(WithdrawStatus.APPLY_FAILURE);
					} else if ("success".equals(status)) {
						detail.setStatus(WithdrawStatus.SUCCESS);
					} else if ("failure".equals(status)) {
						detail.setStatus(WithdrawStatus.FAILURE);
					}
					detail.setTerminal("PC");
					if (!withdrawService.transfer(detail)) {
						jsonMsg = new JsonMsg(1, "提现记录："+id+"操作失败");
						break;
					}
				}
			}
			printJSON(jsonMsg);
			return;
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static List<Integer> splitID(String ids) {
		List<Integer> idList =new ArrayList<Integer>();
		String[] idArr= ids.split(",");
		for (int i = 0; i < idArr.length; i++) {
			idList.add(Integer.parseInt(idArr[i]));
		}
		return idList;
	}
	
	@RequestMapping("/query")
	public String query(){
		return ftl(Thread.currentThread().getStackTrace());
	}
	
	@RequestMapping("/getUserInfo")
	public void getUserInfo(@RequestParam(value="userId") Integer userId) throws Exception {
		FundDetailVo  fundVo=tenderService.getFundDetailVo(userId);
		UserAccountVo vo = userAccountService.selectAccountVoByUserId(userId);
		vo.setAwait(fundVo.getAwaitTotal());
		if(vo != null) {
			super.printJSON(new JsonMsg(-1, "获取信息成功", vo));
		}else {
			super.printJSON(new JsonMsg(0, "获取信息失败", vo));
		}
	}
	

	/**
	 * Description:打开线下提现页面
	 * @auther:fdq
	 * @date :2016年10月20日
	 */
	@RequestMapping(value = "/offLineWithdraw")
	public String offLineWithdraw(){
		return ftl(Thread.currentThread().getStackTrace());
	}
	
	
	/**
	 * Description:线下提现确认
	 * @auther:fdq
	 * @date :2016年10月20日
	 */
	@RequestMapping(value = "/offLineWithdrawSubmit")
	public void offLineWithdrawSubmit(@RequestParam(value="username",required=true) String username,
			@RequestParam(value="ssnCode",required=true) String ssnCode,
			@RequestParam(value="money",required=true) double money){
		try {
			User user=userService.getByName(username);
			if(null == user){
				super.printJSON(new JsonMsg(1, "线下提现失败!不存在该用户！"));
				return;
			}
			int userId = user.getId();
			UserAccount account=userAccountService.getByUserId(userId);
			List<BankCard> bankList = bankCardService.listCardByUserId(userId);
			
			//提现记录表
			WithdrawRecord withdraw = new WithdrawRecord();
			withdraw.setCode(ssnCode);
			withdraw.setUserId(userId);
			withdraw.setCardNo(bankList.get(0).getCardNo());
			withdraw.setMoney(money);
			withdraw.setBalance(money);
			withdraw.setFee(0.0);	
			withdraw.setStatus(WithdrawStatus.SUCCESS);
			withdraw.setTerminal("PC");
			withdraw.setBankNo(bankList.get(0).getBankName());
			withdraw.setIsOffLine("1");//线下提现
			withdraw.setCreateTime(new Date());
			int i = withdrawService.saveOrUpdate(withdraw);
			if(i<1){
				super.printJSON(new JsonMsg(1, "线下提现失败!更新提现记录表失败！"));
				return;
			}
			//用户账户表
			account.setTotalAmount(account.getTotalAmount()-money);  
			account.setBalance(account.getBalance()-money);//可用余额  
			account.setTotalWithdraw(account.getTotalWithdraw()+money);
			i = userAccountService.saveOrUpdate(account);
			if(i<1){
				super.printJSON(new JsonMsg(1, "线下提现失败!更新用户账户表失败！"));
				return;
			}
			
			//资金明细表
			i = rechargeService.addFundRecord(userId,0.0,money,"PC","线下提现",FundRecordType.Type.WITHDRAW.index,0.0,account.getBalance());
			if(i<1){
				super.printJSON(new JsonMsg(1, "线下提现失败!更新资金明细表失败！"));
				return;
			}else{
				super.printJSON(new JsonMsg(-1, "线下提现成功!"));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
}